package net.neptech.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import org.springframework.messaging.converter.StringMessageConverter;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * STOMP方便进行和service-websocket连接
 */

@Service
public class AiStompClientService {

    private static final String WS_URL = "ws://service-websocket:8080/ai-ws"; // 替换为实际地址
    private static final String DESTINATION_TRANSCRIPT = "/app/ai.transcript";
    private static final String DESTINATION_SUMMARY = "/app/ai.summary";

    private StompSession session;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @PostConstruct
    public void connect() {
        WebSocketClient client = new StandardWebSocketClient();
        WebSocketStompClient stompClient = new WebSocketStompClient(client);
        stompClient.setMessageConverter(new StringMessageConverter()); // 简单文本

        try {
            session = stompClient.connect(WS_URL, new StompSessionHandlerAdapter() {
                @Override
                public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
                    System.out.println("✅ AI 模块已连接到 STOMP 服务器: " + WS_URL);
                }
            }).get(30, TimeUnit.SECONDS); // 等待连接建立

        } catch (Exception e) {
            System.err.println("❌ AI 模块连接 STOMP 失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 发送实时字幕
     */
    public void sendTranscript(String conferenceId, String text, boolean isPartial) {
        if (session == null || !session.isConnected()) {
            System.err.println("❌ STOMP 连接未建立，无法发送字幕");
            return;
        }

        try {
            Map<String, Object> payload = new HashMap<>();
            payload.put("conferenceId", conferenceId);
            payload.put("text", text);
            payload.put("partial", isPartial);
            payload.put("timestamp", System.currentTimeMillis());

            String json = objectMapper.writeValueAsString(payload);
            session.send(DESTINATION_TRANSCRIPT, json);
            System.out.println("📤 AI 已发送字幕: " + text + " (partial=" + isPartial + ")");

        } catch (Exception e) {
            System.err.println("❌ 发送字幕失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 发送会议纪要
     */
    public void sendSummary(String conferenceId, String content) {
        if (session == null || !session.isConnected()) {
            System.err.println("❌ STOMP 连接未建立，无法发送纪要");
            return;
        }

        try {
            Map<String, Object> payload = new HashMap<>();
            payload.put("conferenceId", conferenceId);
            payload.put("content", content);
            payload.put("timestamp", System.currentTimeMillis());

            String json = objectMapper.writeValueAsString(payload);
            session.send(DESTINATION_SUMMARY, json);
            System.out.println("📤 AI 已发送会议纪要");

        } catch (Exception e) {
            System.err.println("❌ 发送纪要失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
